//重构需求 5243 取消分配
import {messages} from "share/common";
import React from 'react';
import {connect} from 'react-redux';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import {Input, Button, Form, Checkbox, message, Switch, Icon, Spin, Modal} from 'antd';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import ImageUpload from 'components/image-upload';
import UploadFile from 'components/upload';
import announcementService from 'containers/setting/announcement-information/announcement-information.service';
import 'styles/setting/announcement-information/announcement-information-detail.scss';
import 'braft-editor/dist/braft.css';
import Chooser from 'components/chooser';
import IeFileUpload from 'components/template/ie-file-upload/ie-file-upload'

const FormItem = Form.Item;

class AnnouncementInformationDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleTemp: false,
      loading: false,
      pageLoading: false,
      isOutLink: false,
      isEnabled: true,
      defaultImageList: [],
      imageList: [],
      content: null,
      info: {},
      fileUploadVisible: false,
      announcementList: menuRoute.getRouteItem('announcement-information', 'key'), //公告信息列表页
      tempTarget: {},
      tempImgList: []
    }
  }

  componentDidMount() {
    this.props.params.OID && this.getInfo();
    this.getAnnouncementTemp();
  }

  getInfo = () => {
    this.setState({pageLoading: true});
    announcementService.getAnnouncementDetail(this.props.params.OID)
      .then(res => {
        this.setState({
          pageLoading: false,
          info: res.data,
          isOutLink: res.data.outLink,
          isEnabled: res.data.enable,
          defaultImageList: [res.data.attachmentDTO],
          imageList: [res.data.attachmentDTO],
          content: res.data.content
        })
      })
  };

  getAnnouncementTemp = () => {
    announcementService.getAnnouncementTemp()
      .then(res => {
        this.setState(
          {
            tempImgList: res.data
          }
        )
      })
  };

  onCheckboxChange = (e) => {
    this.setState({isOutLink: e.target.checked})
  };

  //改变状态
  handleStatusChange = (status) => {
    this.setState({isEnabled: status})
  };

  //上传封面图片
  handleUploadImage = (values) => {
    this.setState({imageList: values})
  };

  //提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!this.state.imageList.length) {
          message.error(messages('setting.key47'/*请选择封面图片*/))
        } else {
          this.handleSave(values)
        }
      }
    });
  };

  //保存
  handleSave = (values) => {
    let content = this.state.content;
    //content可以为空，这里就报错了
    let img_arr = [];
    //以下是为了在移动端防止图片过大而无法完全显示的问题
    try {
      img_arr = content.match(/<img.*?>/g);
      img_arr && img_arr.map((img, index) => {
        if (img.match(/width="auto"/) && img.match(/height="auto"/)) {
          img = img.replace(/width="auto"/, '');
          img = img.replace(/height="auto"/, '');
          img = img.replace(/width:auto;height:auto;/, '');
        }
        content = content.replace(content.match(/<img.*?>/g)[index], img)
      });
      //以下是因为移动端无法正确显示<em>和<i>，因此加上css属性实现斜体
      content = content.replace(/<em>/g, '<em style="font-style: italic">');
      content = content.replace(/<i>/g, '<i style="font-style: italic">');
    } catch (e) {
      //content为null,undefined等
    }

    values.enable = this.state.isEnabled;
    values.attachmentOID = this.state.imageList[0].attachmentOID;
    !this.props.tenantMode && (values.companyOID = this.props.company.companyOID);
    values.content = content;
    values.preferredDate = moment(new Date());
    this.props.params.OID && (values.carouselOID = this.props.params.OID);
    this.setState({loading: true});
    if (this.props.params.OID) {
      this.updateAnnouncement(values)
    } else {
      this.newAnnouncement(values)
    }
  };
  updateAnnouncement = (values) => {
    announcementService.updateAnnouncement(values)
      .then(res => {
        this.setState({loading: false});
        this.handleCancel()
      })
      .catch(e => {
        this.setState({loading: false});
      })
  };
  newAnnouncement = (values) => {
    announcementService.newAnnouncement(values)
      .then(res => {
        this.setState({loading: false});
        this.handleCancel()
      })
      .catch(e => {
        this.setState({loading: false});
      })
  };
  //取消
  handleCancel = () => {
    this.context.router.push(this.state.announcementList.url)
  };

  handleContentChange = (content) => {
    this.setState({content})
  };

  //富文本中上传图片
  handleImageUpload = (param) => {
    const formData = new FormData();
    formData.append('attachmentType', 'CARROUSEL_IMAGES');
    formData.append('file', param.file);
    announcementService.handleImageUpload(formData).then(res => {
      param.success({url: res.data.fileURL})
    }).catch(e => {
      param.error();
      message.error(`${messages('setting.key50'/*图片上传失败*/)}，${e.response.data.message}`)
    })
  };
  //上传文件
  handleFileUpload = (fileList) => {
    let content = this.state.content;
    fileList.map(item => {
      content += `<a href="${item.response.fileURL}" target="">${item.response.fileName}</a>`;
    });
    this.editorInstance.setContent(content, 'html');
    this.handleContentChange(content);
    this.setState({fileUploadVisible: false})
  };
  handleFileUploadIE = (response) => {

    let content = this.state.content;
    response.map(item => {
      content += `<a href="${item.fileURL}" target="">${item.fileName}</a>`;
    });
    this.editorInstance.setContent(content, 'html');
    this.handleContentChange(content);
    this.setState({fileUploadVisible: false})
  };

  showTempModal = () => {
    this.setState({visibleTemp: true})
  };
  handleOkTemp = () => {
    let tempImgList = this.state.tempImgList;
    //默认显示的
    // let defaultImageList = this.state.defaultImageList;
    //上传用的
    // let imageList = this.state.imageList;
    let tempTarget = null;
    tempImgList.map(item => {
      if (item.selected) {
        tempTarget = item;
      }
    });

    //如果用户没有选择模板
    if (tempTarget === null) {
      this.setState({visibleTemp: false});
      return;
    }

    tempTarget.iconUrl = tempTarget.templateUrl;
    tempTarget.fileURL = tempTarget.templateUrl;
    tempTarget.fileName = tempTarget.templateName;

    this.setState({
      visibleTemp: false,
      tempTarget: tempTarget,
      imageList: [tempTarget],
      defaultImageList: [tempTarget]
    })

  };
  handleCancelTemp = () => {
    this.setState({visibleTemp: false})
  };
  selectTempImg = (item) => {
    let tempImgList = this.state.tempImgList;
    tempImgList.map(item => {
      item.selected = false;
    });
    item.selected = true;
    this.setState({
      tempImgList
    })
  };

  renderImgList = (imgs) => {
    if (imgs.length < 1) {
      return <div className="img-radio">
        {/*没有设置模板*/}
        {messages('setting.key51'/*没有设置模板*/)}
      </div>
    } else {
      return <div className="img-list-wrap">
        {imgs.map((item, index) => {
          return <div className="img-wrap f-left" key={index} onClick={() => {
            this.selectTempImg(item)
          }}>
            <div className="img-target">
              <img src={item.templateUrl}/>
            </div>
            <div className="img-radio">
              {item.selected ? <Icon type="check-circle" className="checked"/> : <Icon type="check-circle"/>}
              &nbsp;&nbsp;
              {item.templateName}
            </div>
          </div>
        })}
        <div className="clear"/>
      </div>
    }
  };
  companyChange = (companys) => {
  }

  render() {
    const {
      loading, pageLoading, isEnabled,
      defaultImageList, info, content, fileUploadVisible
    } = this.state;
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 14, offset: 1},
    };
    const controls = [
      'undo', 'redo', 'split', 'text-align', 'font-size', 'font-family', 'line-height', 'text-color',
      'bold', 'italic', 'underline', 'strike-through', 'superscript',
      'subscript', 'split', 'headings', 'list_ul', 'list_ol',
      'blockquote', 'code', 'split', 'link', 'split', 'media'
    ];
    const extendControls = [{
      type: 'button',
      text: <Icon type="file-add"/>,
      hoverTitle: messages('setting.key52'/*上传文件*/),
      className: 'file-add',
      onClick: () => this.setState({fileUploadVisible: true})
    }];

    return (
      <div className="announcement-information-detail">
        <Spin spinning={pageLoading}>
          <Form className="form-container">
            <FormItem {...formItemLayout} label={messages('setting.key54'/*标题*/)}>
              {getFieldDecorator('title', {
                rules: [{
                  required: true,
                  message: messages("common.please.enter"/*请输入*/)
                }, {
                  max: 256,
                  message: messages('setting.key2208')/*最多输入256个字*/,
                }],
                initialValue: info.title
              })(
                <Input
                  disabled={!this.props.tenantMode}
                  placeholder={messages("common.please.enter"/*请输入*/)}/>
              )}
            </FormItem>


            {this.props.tenantMode && <FormItem {...formItemLayout} label={messages('setting.key730')/*适用公司*/}>
              {getFieldDecorator('companys', {
                initialValue: info.companys || new Array()
              })(
                <Chooser placeholder={messages('setting.key1833')/*不填表明适用于所有公司*/}
                         type="available_company"
                         labelKey="name"
                         valueKey="id"
                         disabled={!this.props.tenantMode}
                         onChange={this.companyChange}/>
              )}
            </FormItem>}

            <FormItem {...formItemLayout} label={messages('setting.key55'/*跳转外部链接*/)}>
              {getFieldDecorator('outLink', {
                valuePropName: 'checked',
                initialValue: info.outLink
              })(
                <Checkbox
                  disabled={!this.props.tenantMode}
                  onChange={this.onCheckboxChange}>
                  {messages('setting.key56'/*勾选该选项，则直接按正文中第一个链接跳转到链接页面*/)}
                </Checkbox>
              )}
            </FormItem>

            <FormItem {...formItemLayout}
                      label={<span className="ant-form-item-required">
                  {messages('setting.key57'/*封面图片*/)}</span>}
            >
              <Button type="primary"
                      disabled={!this.props.tenantMode}
                      onClick={this.showTempModal}>
                {/*从模板中选择*/}
                {messages('setting.key58'/*从模板中选择*/)}
              </Button>
              <br/>
              &nbsp;
              <br/>
              <ImageUpload attachmentType="CARROUSEL_IMAGES"
                           uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                           maxNum={1}
                           disabled={!this.props.tenantMode}
                           fileType={['jpg', 'jpeg', 'bmp', 'gif', 'png']}
                           fileSize={5}
                           defaultFileList={defaultImageList}
                           isShowDefault={true}
                           onChange={this.handleUploadImage}/>
              <div
                className="image-attention"> {messages('setting.key1662')/*推荐尺寸：1200*640 | 格式：'jpg','jpeg','bmp','gif','png' | 大小：3M以内*/}
              </div>
            </FormItem>
            <FormItem {...formItemLayout} label={messages("common.column.status"/*状态*/)}>
              {getFieldDecorator('enable')(
                <div>
                  <Switch checked={isEnabled}
                          disabled={!this.props.tenantMode}
                          checkedChildren={<Icon type="check"/>}
                          unCheckedChildren={<Icon type="cross"/>}
                          onChange={this.handleStatusChange}/>
                  <span
                    className="enabled-type">{isEnabled ? messages("common.status.enable") : messages("common.status.disable")}</span>
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('setting.key60'/*正文*/)}>
              <BraftEditor height={200}
                           controls={controls}
                           language={this.props.language.locale}
                           contentFormat="html"
                           initialContent={content}
                           extendControls={extendControls}
                           // fontFamilies={[
                           //   {
                           //     name: 'Araial',
                           //     family: 'Arial, Helvetica, sans-serif'
                           //   }, {
                           //     name: 'Georgia',
                           //     family: 'Georgia, serif'
                           //   }, {
                           //     name: 'Impact',
                           //     family: 'Impact, serif'
                           //   }, {
                           //     name: 'Monospace',
                           //     family: '"Courier New", Courier, monospace'
                           //   }, {
                           //     name: 'Tahoma',
                           //     family: 'tahoma, arial, "Hiragino Sans GB", 宋体, sans-serif'
                           //   },
                           //   {
                           //     name: '方正',
                           //     family: 'Arial, arial, "Hiragino Sans GB", 宋体, sans-serif'
                           //   }
                           // ]}
                           media={{
                             image: true,
                             video: false,
                             audio: false,
                             externalMedias: {
                               image: false,
                               video: false,
                               audio: false
                             },
                             uploadFn: this.handleImageUpload
                           }}
                           ref={instance => this.editorInstance = instance}
                           onChange={this.handleContentChange}/>
            </FormItem>
            <div className="btn">
              <Button type="primary"
                      loading={loading}
                      disabled={!this.props.tenantMode}
                      onClick={this.handleSubmit}>
                {messages('common.save')}
              </Button>
              <Button onClick={this.handleCancel} className="cancel-btn">{messages('common.back')}</Button>
            </div>
          </Form>
        </Spin>
        {fileUploadVisible && (
          <Modal title={messages('setting.key52'/*上传文件*/)}
                 visible={fileUploadVisible}
                 onCancel={() => this.setState({fileUploadVisible: false})}
                 footer={<Button onClick={() => this.setState({fileUploadVisible: false})}>
                   {messages('common.cancel')}
                 </Button>}>
            {(window.isSafari || window.ISIE) && <IeFileUpload attachmentType="OTHER"
                           uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                           fileSize={10}
                           showMaxNum={false}
                           token={this.props.authToken.access_token}
                           onChange={this.handleFileUploadIE}
            />}
            {!window.isSafari && !window.ISIE && <UploadFile uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                         attachmentType="OTHER"
                         fileNum={1}
                         needAllResponse={true}
                         uploadHandle={this.handleFileUpload}/>}
          </Modal>
        )}
        {/*选择轮播图模板的弹窗*/}
        <Modal
          title={messages('setting.key63'/*选择模板*/)}//选择模板
          width={490}
          className="select-carousel-temp-modal"
          maskCloseable={false}
          visible={this.state.visibleTemp}
          onOk={this.handleOkTemp}
          onCancel={this.handleCancelTemp}
        >
          {this.renderImgList(this.state.tempImgList)}
        </Modal>
      </div>
    )
  }
}

AnnouncementInformationDetail.contextTypes = {
  router: React.PropTypes.object
};
function mapStateToProps(state) {
  return {
    authToken: state.main.authToken,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

const WrappedAnnouncementInformationDetail = Form.create()(AnnouncementInformationDetail);

export default connect(mapStateToProps)(WrappedAnnouncementInformationDetail);
